package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 负责与指定客户端进行一次HTTP交互
 * HTTP协议要求客户端与服务端采取一问一答的交互规则.
 * 并在交互完毕后断开TCP连接
 * <p>
 * 因此,这里处理一次HTTP交互采取的过程分为三部分:
 * 1:解析请求(读取客户端发送过来的HTTP请求内容)
 * 2:处理请求(分析请求信息确定客户端意图,并进行对应的处理)
 * 3:发送响应(给浏览器发送一个HTTP中的响应,将处理结果回复给浏览器)
 */

public class ClientHandler_Self implements Runnable {
    private Socket socket;

    public ClientHandler_Self(Socket socket) {
        this.socket = socket;
    }

    public void run() {

        try {
            // http://localhost:8088
            //1.解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            //2.处理请求
            String path = request.getUri();

            System.out.println("抽象路径:"+path);
            File file = new File("./webapps/"+path);
            File file2 = new File("./webapps/root/404.html");

            if (file.exists()&&file.isFile()){
            //3 发送响应

            //3.1发送状态行
            String line = "HTTP/1.1 200 OK";
            println(line);
            //3.2发送响应头
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());
            println("");

            //3.3发送响应正文
            FileInputStream fis = new FileInputStream(file);
            OutputStream out = socket.getOutputStream();
            byte[] data = new byte[1024*10];
            int len;
            while ((len = fis.read(data))!=-1){
                out.write(data,0,len);
            }
            System.out.println("响应发送完毕!");
            }else {
                String line2 = "HTTP/1.1 404 NotFound";
                println(line2);
                println("Content-Type: text/html");
                println("Content-Length: "+file2.length());
                println("");


                FileInputStream fis2 = new FileInputStream(file2);
                OutputStream out2 = socket.getOutputStream();
                byte[] data2 = new byte[1024*10];
                int len;
                while ((len = fis2.read(data2))!=-1){
                    out2.write(data2,0,len);
                }
                System.out.println("响应发送完毕!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //交互后与客户端断开连接(协议要求)
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        //
        out.write(data);
        out.write(13);//单独发送回车符
        out.write(10);//单独发送换行符
    }


}
